package problem40_Combination_Sum2;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Solution {
	private final List<List<Integer>> result=new LinkedList<>();
	private final List<Integer> current=new LinkedList<>();
	public List<List<Integer>> combinationSum2(int[] candidates, int target) {
	    Arrays.sort(candidates);
	    backtracking(candidates,target,-1);
		return result;
	}
	
	private void backtracking(int[] candidates,int rest_target,int lastUsed){
		if(rest_target==0)
			result.add(new LinkedList<>(current));
		int removed=-1;
		for(int i=lastUsed+1;i<candidates.length&&candidates[i]<=rest_target;i++){
			if(candidates[i]==removed) continue;
			current.add(candidates[i]);
			backtracking(candidates,rest_target-candidates[i],i);
			removed=current.remove(current.size()-1);
		}
	}
	
	public static void main(String[] args){
		System.out.println(new Solution().combinationSum2(new int[]{1, 2, 7, 6, 1, 5}, 8));
	}
}
